package com.example.yls.demoa;

import android.app.DatePickerDialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyService extends Service {
    private boolean islive=true;
    private BroadcastReceiver mybroadcastReceiver;
    int limit = 0;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (islive){
                    Intent intent = new Intent();
                    intent.setAction("TIME_CHANGED");
                    intent.putExtra("TIME",getStrTime());
                    sendBroadcast(intent);




                    try {
                        Thread.sleep(1000);
                        limit++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (limit==10){
                        islive=false;

                    }
                }

            }
        }).start();


        Log.e("MyService","thread ="+Thread.currentThread().getId());

        Intent intent = new Intent(MyService.this,WeatherActivity.class);

        PendingIntent pi = PendingIntent.getActivity(MyService.this,1001,intent,0);

        Notification notification = new Notification.Builder(MyService.this)
                .setContentTitle("通知标题")
                .setContentText("通知内容")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pi)
                .build();

        startForeground(1,notification);
    }

    private String getStrTime() {

        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        return format.format(date);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

            islive=false;


    }

}
